package com.midele.goodstuff.ui.search.screen

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.midele.goodstuff.R
import com.midele.goodstuff.ui.component.TagItem
import com.midele.goodstuff.ui.search.SearchPageIntent
import com.midele.goodstuff.ui.search.SearchPageState
import com.midele.goodstuff.util.LogUtils
import com.midele.goodstuff.viewmodel.SearchViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@Composable
internal fun SearchRoute(
    modifier: Modifier = Modifier,
    viewModel: SearchViewModel = hiltViewModel(),
    navController: NavHostController,
) {
    SearchScreen(viewModel,navController)
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun SearchScreen(searchViewModel:SearchViewModel,navController: NavController) {


    val searchPageState by searchViewModel.searchPageState.collectAsState()

    val scope = rememberCoroutineScope()
    val snackbarHostState = remember { SnackbarHostState() }

    val openAlertDialog = remember { mutableStateOf(false) }

    LogUtils.d("SearchScreen", "SearchScreen>>>>>>>>>>>>>>>>>")

    searchViewModel.processIntent(SearchPageIntent.GetSearchHistoryData)
    searchViewModel.processIntent(SearchPageIntent.GetRecommendData)

    Scaffold(
        snackbarHost = {
            SnackbarHost(hostState = snackbarHostState)
        },
    ){ padding ->

        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black)
                .padding(start = 16.dp, end = 16.dp)
        ) {

            Spacer(modifier = Modifier
                .fillMaxWidth()
                .height(44.dp))
            ConstraintLayout(modifier = Modifier.fillMaxWidth()) {
                val (backLayout, searchLayout, btnLayout) = createRefs()
                Image(
                    painter = painterResource(id = R.mipmap.ic_white_back_arrow),
                    contentDescription = null,
                    modifier = Modifier
                        .width(24.dp)
                        .height(24.dp)
                        .constrainAs(backLayout) {
                            top.linkTo(searchLayout.top)
                            bottom.linkTo(searchLayout.bottom)
                            start.linkTo(parent.start)
                        }.clickable {
                            navController.navigateUp()
                        }
                )
                BasicTextField(
                    value = searchPageState.searchText,
                    /*    leadingIcon = {
                             Image(
                                 painter = painterResource(id = R.mipmap.ic_white_search),
                                 contentDescription = null,
                                 modifier = Modifier
                                     .width(24.dp)
                                     .height(24.dp)
                             )
                         },
                         label = { Text("请输入你想要的物品", color = Color(0xFF646566), fontSize = 14.sp) },*/
                    decorationBox = { innerTextField ->
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(100.dp) // 设置高度
                                .background(
                                    Color(0xFF211C18),
                                    shape = RoundedCornerShape(100.dp)
                                ) // 黑色背景 + 圆角
                                .padding(16.dp), // 内边距
                            contentAlignment = Alignment.CenterStart // 文本左对齐
                        ) {
                            innerTextField() // 渲染输入内容
                        }
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                        .background(Color.Transparent)
                        .constrainAs(searchLayout) {
                            top.linkTo(parent.top)
                            start.linkTo(backLayout.end, margin = 8.dp)
                            end.linkTo(parent.end, margin = 20.dp)
                            width = Dimension.fillToConstraints
                        },
                    //shape = RoundedCornerShape(100.dp),
                    onValueChange = {
                        LogUtils.d("SearchScreen", "SearchScreen searchData>>> $it>>>>>>>>>>>>>>>>>")
                        searchViewModel.processIntent(SearchPageIntent.SearchGoodsData(it))
                    },
                )

                Text(
                    text = "搜索",
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF121212),
                    fontSize = 14.sp,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .clip(RoundedCornerShape(100.dp))
                        .background(Color(0xFFFCE9C1))
                        .padding(top = 6.dp, bottom = 6.dp, start = 14.dp, end = 14.dp)
                        .constrainAs(btnLayout) {
                            end.linkTo(parent.end, margin = 20.dp)
                            top.linkTo(searchLayout.top)
                            bottom.linkTo(searchLayout.bottom)
                        },

                    )
            }

            if(searchPageState.searchText == ""){
                SearchHistoryScreen(padding,searchViewModel,searchPageState,scope,snackbarHostState,openAlertDialog)
            }else{
                SearchDataScreen()
            }

            if(openAlertDialog.value){
                DeleteHistoryDialog(
                    onDismissRequest = { openAlertDialog.value = false },
                    onConfirmation = {
                        searchViewModel.processIntent(SearchPageIntent.DeleteSearchHistory(""))
                    }
                )
            }

        }

    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun SearchHistoryScreen(padding: PaddingValues,searchViewModel:SearchViewModel,searchPageState: SearchPageState,scope: CoroutineScope,snackbarHostState: SnackbarHostState,openAlertDialog: MutableState<Boolean>) {

    LogUtils.d("SearchScreen", "SearchHistoryScreen 11111111111>>>>>>>>>>>>>>>>>")

 /*   if(searchPageState.searchHistoryList.isEmpty()){
        searchViewModel.processIntent(SearchPageIntent.GetSearchHistoryData)
    }

    if(searchPageState.recommendList.isEmpty()){
        searchViewModel.processIntent(SearchPageIntent.GetRecommendData)
    }*/

   // val tags = listOf("Jetpack", "Compose", "Kotlin", "Android", "UI", "开发", "框架", "跨平台")
    //val recommands = listOf("recommands", "西亚天珠")


        Spacer(modifier = Modifier.height(16.dp))
        Box(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            Text(
                text = "历史搜索",
                fontWeight = FontWeight.Bold,
                color = Color.White,
                fontSize = 14.sp,
                textAlign = TextAlign.Center,
                modifier = Modifier
                    .align(Alignment.CenterStart)
            )

            Image(
                painter = painterResource(id = R.mipmap.ic_history_delete),
                contentDescription = null,
                modifier = Modifier
                    .align(Alignment.CenterEnd)
                    .width(20.dp)
                    .height(20.dp)
                    .clickable {
                        openAlertDialog.value = true
                    }
            )
        }
        Spacer(modifier = Modifier.height(16.dp))

        FlowRow(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            searchPageState.searchHistoryList.forEach { tag ->
                TagItem(text = tag, onClick = { selTag ->
                    LogUtils.d("SearchScreen", "点击了333$selTag")
                    scope.launch {
                        snackbarHostState.showSnackbar("点击了$selTag")
                        LogUtils.d("SearchScreen", "点击了333$selTag")
                    }
                })
            }
        }

        Spacer(modifier = Modifier.height(16.dp))
        ConstraintLayout(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(20.dp))
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(Color(0xFFFCE9C1).copy(alpha = 0.1f), Color(0xFF121212)), // 起始到结束颜色
                        start = Offset(x = 0f, y = 0f),     // 顶部起始
                        end = Offset(x = 0f, y = Float.POSITIVE_INFINITY) // 底部无限延伸
                    )
                )
                .padding(start = 8.dp, end = 8.dp)



        ) {
            val (titleLayout, itemLayout) = createRefs()
            Box(modifier = Modifier
                .fillMaxWidth()
                .constrainAs(titleLayout) {
                    top.linkTo(parent.top)
                },) {
                Text(
                    text = "推荐搜索",
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFFFCE9C1),
                    fontSize = 14.sp,
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .align(Alignment.TopStart)
                        .padding(top = 12.dp)
                )

                Image(
                    painter = painterResource(id = R.mipmap.ic_search_recommand_title),
                    contentDescription = null,
                    contentScale = ContentScale.Fit,
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                )
            }

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFF121212))
                    .padding(start = 12.dp, end = 12.dp)
                    .constrainAs(itemLayout) {
                        top.linkTo(parent.top, margin = 42.dp)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                    }) {
                searchPageState.recommendList.forEachIndexed { index, recommandItem ->
                    Box(modifier = Modifier.fillMaxWidth().height(52.dp), contentAlignment = Alignment.Center) {
                        Text(
                            text = recommandItem,
                            fontWeight = FontWeight.Bold,
                            color = Color.White,
                            fontSize = 14.sp,
                            textAlign = TextAlign.Center,
                            modifier = Modifier
                                .align(Alignment.CenterStart)
                        )

                        Image(
                            painter = painterResource(id = R.mipmap.ic_search_recommand_item),
                            contentDescription = null,
                            contentScale = ContentScale.Fit,
                            modifier = Modifier
                                .align(Alignment.CenterEnd)
                        )
                    }
                    if (index != searchPageState.recommendList.size - 1) {
                        Spacer(modifier = Modifier.height(0.5.dp).fillMaxWidth().background(Color(0xFF646566)))
                    }
                }
            }
        }
}


@Composable
fun SearchDataScreen() {

    LogUtils.d("SearchScreen", "SearchDataScreen 2222>>>>>>>>>>>>>>>>>")

    LazyVerticalGrid(
        columns = GridCells.Fixed(2),
        contentPadding = PaddingValues(horizontal = 16.dp),
        verticalArrangement = Arrangement.spacedBy(9.dp),
        horizontalArrangement = Arrangement.spacedBy(9.dp),
        modifier = Modifier
            .padding(bottom = 20.dp, top = 16.dp)
    ) {
        items(6) {
            ConstraintLayout(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(228.dp)
                    .background(color = Color(0xFF211C18), shape = RoundedCornerShape(16.dp))
            ) {

                val (imgLogoLayout, itemTagLayout, itemNameLayout, itemHeaderLogoLayout,itemUserNameLayout, itemLikeLayout, itemLikeAccountLayout) = createRefs()

                Image(
                    painter = painterResource(id = R.drawable.ic_good_demo), // 替换为你的图片资源ID
                    contentDescription = "Logo Image", // 图片描述，对于无障碍很重要
                    contentScale = ContentScale.Crop, // 图片填充模式，根据你的需求选择合适的模式
                    modifier = Modifier
                        .clip(RoundedCornerShape(10.dp))
                        .height(160.dp)
                        .constrainAs(imgLogoLayout) {
                            top.linkTo(parent.top, margin = 8.dp)
                            start.linkTo(parent.start, margin = 8.dp)
                            end.linkTo(parent.end, margin = 8.dp)
                            width = Dimension.fillToConstraints
                        }

                )

                Text(
                    text = "至纯天珠",
                    color = Color.White,
                    fontSize = 12.sp,
                    modifier = Modifier
                        .background(color = Color(0xB3000000), shape = RoundedCornerShape(100.dp))
                        .constrainAs(itemTagLayout) {
                            top.linkTo(parent.top, margin = 10.dp)
                            start.linkTo(parent.start, margin = 14.dp)
                        }
                )
                Text(
                    text = "货真价实 极品天珠",
                    color = Color.White,
                    fontSize = 14.sp,
                    modifier = Modifier
                        .constrainAs(itemNameLayout) {
                            start.linkTo(parent.start, margin = 12.dp)
                            bottom.linkTo(parent.bottom, margin = 32.dp)
                        }
                )
                Image(
                    painter = painterResource(id = R.mipmap.ic_tag_jewelry_sel), // 替换为你的图片资源ID
                    contentDescription = "Logo Image", // 图片描述，对于无障碍很重要
                    contentScale = ContentScale.Fit, // 图片填充模式，根据你的需求选择合适的模式
                    modifier = Modifier
                        .size(12.dp)
                        .clip(CircleShape)
                        .constrainAs(itemHeaderLogoLayout) {
                            start.linkTo(parent.start, margin = 12.dp)
                            bottom.linkTo(parent.bottom, margin = 11.dp)
                        }
                )
                Text(
                    text = "用户名称",
                    color = Color(0xFF969799),
                    fontSize = 10.sp,
                    modifier = Modifier
                        .constrainAs(itemUserNameLayout) {
                            start.linkTo(itemHeaderLogoLayout.end, margin = 4.dp)
                            bottom.linkTo(parent.bottom, margin = 9.dp)
                        }
                )

                Image(
                    painter = painterResource(id = R.mipmap.ic_unlike_good), // 替换为你的图片资源ID
                    contentDescription = "Logo Image", // 图片描述，对于无障碍很重要
                    contentScale = ContentScale.Fit, // 图片填充模式，根据你的需求选择合适的模式
                    modifier = Modifier
                        .size(18.dp)
                        .constrainAs(itemLikeLayout) {
                            end.linkTo(itemLikeAccountLayout.start, margin = 2.dp)
                            bottom.linkTo(parent.bottom, margin = 11.dp)
                        }
                )
                Text(
                    text = "999",
                    color = Color(0xFF969799),
                    fontSize = 12.sp,
                    modifier = Modifier
                        .constrainAs(itemLikeAccountLayout) {
                            end.linkTo(parent.end, margin = 12.dp)
                            bottom.linkTo(parent.bottom, margin = 9.dp)
                        }
                )


            }
        }
    }
}

@Composable
fun DeleteHistoryDialog(
    onDismissRequest: () -> Unit,
    onConfirmation: () -> Unit,
) {
    Dialog(onDismissRequest = { onDismissRequest() }) {

        ConstraintLayout(modifier = Modifier
                .width(275.dp)
        ){
            Image(
                painter = painterResource(id = R.drawable.ic_dialog_bg), // 替换为你的图片资源ID
                contentDescription = "Logo Image", // 图片描述，对于无障碍很重要
                contentScale = ContentScale.Fit, // 图片填充模式，根据你的需求选择合适的模式
            )

            val (dialogTitle, dialogContent, dialogBtnLayout) = createRefs()

            Text(
                text = "温馨提示",
                color = Color.White,
                fontSize = 16.sp,
                modifier = Modifier
                    .constrainAs(dialogTitle) {
                        top.linkTo(parent.top, margin = 24.dp)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                    }
            )

            Text(
                text = "确定删除所有搜索历史吗？",
                color = Color(0xFF969799),
                fontSize = 14.sp,
                modifier = Modifier
                    .constrainAs(dialogContent) {
                        top.linkTo(dialogTitle.bottom, margin = 12.dp)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                    }
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .constrainAs (dialogBtnLayout){
                        bottom.linkTo(parent.bottom, margin = 24.dp)
                        start.linkTo(parent.start, margin = 24.dp)
                        end.linkTo(parent.end,24.dp)
                    },
                horizontalArrangement = Arrangement.Center,
            ) {
                TextButton(
                    onClick = { onDismissRequest() },
                    modifier = Modifier.padding(top = 11.dp, bottom = 11.dp, start = 35.dp, end = 35.dp).background(Color(0xFF323233),
                        shape = RoundedCornerShape(100.dp)),
                ) {
                    Text("取消", color = Color.White, fontSize = 16.sp)
                }
                TextButton(
                    onClick = { onConfirmation() },
                    modifier = Modifier.padding(top = 11.dp, bottom = 11.dp, start = 35.dp, end = 35.dp).background(
                        brush = Brush.linearGradient(
                            colors = listOf(Color(0xFFFCE9C1), Color(0xFFF3C5B2)), // 起始到结束颜色
                            start = Offset(x = 0f, y = 0f),     // 顶部起始
                            end = Offset(x = 0f, y = Float.POSITIVE_INFINITY) // 底部无限延伸
                        ),
                        shape = RoundedCornerShape(100.dp),
                    ),
                ) {
                    Text("确认", color = Color(0xFF121212), fontSize = 16.sp,)
                }
            }

        }
    }
}
